package com.example.demo

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.base.net.ApiService
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class DemoViewModel @Inject constructor(val apiService: ApiService):ViewModel() {
    //可能一个界面会有多个意图（点击事件，请求数据,访问数据库）  用来接收意图
    val channel = Channel<DemoIntent>()
    //记录当前请求的状态 //默认值 加载中
    private var _state = MutableStateFlow<DemoState>(DemoState.onLoading)
    //对外暴露一个state
    val uiState:StateFlow<DemoState>
        get() = _state


    //定义登录方法
    fun login(password:String,username:String){
        viewModelScope.launch {
            apiService.login(password, username)
                //切换成子线程
                .flowOn(Dispatchers.IO)
                //进行异常处理
                .catch {
                    Log.d("sss", "login:请求失败${it.message} ")
                }
                //接收数据并处理
                .collect{
                    if(it.code==200){
                        _state.value = DemoState.onSuccess(it.data)
                    }else{
                        _state.value = DemoState.onError(it.message)
                    }
                }
        }
    }
    fun register(password:String,username:String){
        viewModelScope.launch {
            apiService.login(password, username)
                //切换成子线程
                .flowOn(Dispatchers.IO)
                //进行异常处理
                .catch {
                    Log.d("sss", "login:请求失败${it.message} ")
                }
                //接收数据并处理
                .collect{
                    if(it.code==200){
                        _state.value = DemoState.onSuccess(it.data)
                    }else{
                        _state.value = DemoState.onError(it.message)
                    }
                }
        }
    }

    init {
        viewModelScope.launch {
            channel.receiveAsFlow().collect{
                when(it){
                    is DemoIntent.login -> {login(it.password,it.username)}
                    is DemoIntent.register -> {
                        register(it.password,it.username)
                    }
                }
            }
        }
    }
}